package com.starblink.android.basic.network.interceptor

import com.apollographql.apollo3.api.ApolloRequest
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.Error
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.interceptor.ApolloInterceptor
import com.apollographql.apollo3.interceptor.ApolloInterceptorChain
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.util.log.YYLogUtils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onEach

/**
 * 单独处理
 */
class SwitchSiteErrorApolloInterceptor(
) : ApolloInterceptor {

    override fun <D : Operation.Data> intercept(
        request: ApolloRequest<D>,
        chain: ApolloInterceptorChain
    ): Flow<ApolloResponse<D>> {
        return chain.proceed(request).onEach { response ->
            if (response.errors != null) {
                var error: Error = response.errors!!.first()
                var extensions: Map<String, Any?>? = error.extensions
                if (extensions != null) {
                    var code = extensions["code"]
                    //code为空 则为网络异常 如参数传错
                    if (code != null) {
                        when (code) {
                            "201012001" -> {
                                SpmTrackHandler.siteStatusHasSwitch = true
                                FlowBus.boolFlowBusNotify(FlowConst.SWITCH_SITE)
                                YYLogUtils.e(" -----> The site belong to is wrong")
                            }
                        }
                    } else {
                        if (error.message.contains("The site belong to is wrong")) {
                            SpmTrackHandler.siteStatusHasSwitch = true
                            FlowBus.boolFlowBusNotify(FlowConst.SWITCH_SITE)
                            YYLogUtils.e(" -----> The site belong to is wrong ++")
                        }
                    }
                }
            }
        }
    }
}